package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.LoginDto;
import com.heima.utils.common.AppJwtUtil;
import com.itheima.mapping.ApUserLoginMapping;
import com.itheima.service.ApUserService;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.asn1.cms.DigestedData;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserLoginMapping, ApUser> implements ApUserService {

    @Override
    public ResponseResult login(LoginDto dto) {
        //判断手机号,密码是否正确
        //不为空正常登录
        HashMap<String, Object> map = new HashMap<>();
        if(!StringUtils.isEmpty(dto.getPhone()) && !StringUtils.isEmpty(dto.getPassword())){
            //获取手机号,根据手机获取用户对象
            ApUser apUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if (apUser != null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            //获取密码
            String salt = apUser.getSalt();
            String password = apUser.getPassword();
            String pwd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            //判断密码是否成功,不成功报错
            if (!pwd.equals(dto.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //返回数据
            apUser.setPassword("");
            apUser.setSalt("");
            map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
            map.put("user",apUser);
          return ResponseResult.okResult(map);
        }else {
            //游客登录
            map.put("token",AppJwtUtil.getToken(0l));
            return ResponseResult.okResult(map);
        }
    }
}
